package com.wanglin.jetpacktest

import android.annotation.SuppressLint
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.core.content.edit
import androidx.lifecycle.ViewModelProvider
import com.wanglin.jetpacktest.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    lateinit var viewModel: MainViewModel
    lateinit var sp:SharedPreferences

    private lateinit var binding:ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)


        binding= ActivityMainBinding.inflate(layoutInflater)
        val view=binding.root
        setContentView(view)

        lifecycle.addObserver(MyObserver(lifecycle))

        sp=getPreferences(MODE_PRIVATE)
        val counter= sp.getInt("counter",0)



        viewModel= ViewModelProvider(this,MainViewModelFactory(counter)).get(MainViewModel::class.java)


        viewModel.counter.observe(this){
            binding.infoText.text=it.toString()
        }
        binding.plusOneBtn.setOnClickListener {
            viewModel.plusOne()

        }

        binding.clearBtn.setOnClickListener {
            viewModel.clear()

        }

        binding.getUserBtn.setOnClickListener {
            val userId=(0..10000).random().toString()
            viewModel.getUser(userId)


        }

        viewModel.user.observe(this){
            binding.infoText.text=it.name
        }





    }



    @SuppressLint("CommitPrefEdits")
    override fun onDestroy() {
        super.onDestroy()
        sp.edit{
            putInt("counter",viewModel.counter.value?:0)
        }
    }


}